package com.vilen.weixin.msg;

import com.vilen.weixin.json.TemplateMsg;
import com.vilen.weixin.kit.WeixinKit;
import com.vilen.weixin.model.WeixinContext;
import com.vilen.weixin.model.WeixinFinalValue;
import com.vilen.weixin.util.JsonUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.*;

/**
 * Created by Administrator on 2016/2/9.
 */
public class MessageKit {
    private static Map<String,String> replyMsgs = new HashMap<String, String>();
    static {
        replyMsgs.put("123","你输入了123");
        replyMsgs.put("hello","world");
        replyMsgs.put("run","祝你一路平安");
    }

    public static Map<String,String> reqMsg2Map(HttpServletRequest request)throws IOException {
        String xml = req2xml(request);
        try {
            Map<String,String> maps = new HashMap<String, String>();
            Document document = DocumentHelper.parseText(xml);
            Element root = document.getRootElement();
            List<Element> eles = root.elements();
            for (Element e: eles) {
                maps.put(e.getName(),e.getTextTrim());
            }
            return maps;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String req2xml (HttpServletRequest request) throws IOException {
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = null;
        StringBuffer sb = new StringBuffer();
        while((str=br.readLine())!=null) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static String handlerMsg(Map<String, String> msgMap) throws IOException {
        String msgType = msgMap.get("MsgType");
        if(WeixinFinalValue.MSG_EVENT_TYPE.equals(msgType)) {

        }else if(msgType.equals(WeixinFinalValue.MSG_TEXT_TYPE)){
            return textTypeHandler(msgMap);
        } else if(msgType.equals(WeixinFinalValue.MSG_IMAGE_TYPE)) {
            return imageTypeHandler(msgMap,"HTjNHPk_q6NaeVolsN1VnwkIClFfy5MXpWKA6t9Yiv-NltObTUn5HMi6YpBMyZR-");
        }
        return null;
    }

    private static String imageTypeHandler(Map<String, String> msgMap,String mediaId) throws IOException {
        Map<String,String> map = new HashMap<String, String>();
        map.put("ToUserName",msgMap.get("FromUserName"));
        map.put("FromUserName",msgMap.get("ToUserName"));
        map.put("CreateTime",new Date().getTime()+"");
        map.put("MsgType","image");
        map.put("Image","<MediaId>"+mediaId+"</MediaId>");
        return map2xml(map);
    }

    private static String textTypeHandler(Map<String, String> msgMap) throws IOException {
        Map<String,String> map = new HashMap<String, String>();
        map.put("ToUserName",msgMap.get("FromUserName"));
        map.put("FromUserName",msgMap.get("ToUserName"));
        map.put("CreateTime",new Date().getTime()+"");
        map.put("MsgType","text");
        String replyContent = "你请求的消息的内容不正确!";
        String con = msgMap.get("Content");
        if (replyMsgs.containsKey(con)) {
            replyContent = replyMsgs.get(con);
        }
        map.put("Content",replyContent);

        return map2xml(map);
    }

    public static String map2xml(Map<String, String> map) throws IOException {
        Document d = DocumentHelper.createDocument();
        Element root = d.addElement("xml");
        Set<String> keys = map.keySet();
        for (String key: keys) {
            root.addElement(key).addText(map.get(key));
        }
        StringWriter sw = new StringWriter();
        //d.write(sw); &lt 格式不对
        XMLWriter xw = new XMLWriter(sw);
        xw.setEscapeText(false);
        xw.write(d);
        return sw.toString();
    }

    public static String postTemplateMsg(TemplateMsg tm) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            String url = WeixinFinalValue.SEND_TEMPLATE_MSG;
            url = url.replace("ACCESS_TOKEN",WeixinFinalValue.TEMP_AT);
            HttpPost post = new HttpPost(url);
            String json = JsonUtil.getInstance().obj2json(tm);
            StringEntity entity = new StringEntity(json, ContentType.create("application/json","UTF-8"));
            post.addHeader("Content-Type","application/json");
            post.setEntity(entity);
            response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if(status>=200&&status<300) {
                String str = EntityUtils.toString(response.getEntity());
                System.out.println(str);
                return str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) {
                    client.close();
                }
                if(response!=null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String postTemplateMsg1(TemplateMsg tm){
        String url = WeixinFinalValue.SEND_TEMPLATE_MSG;
        url = url.replace("ACCESS_TOKEN",WeixinFinalValue.TEMP_AT);
        String json = JsonUtil.getInstance().obj2json(tm);
        return WeixinKit.postReq(url,json,"application/json");
    }
}
